from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
import re,redis,json,time
# Create your views here.



import  jwt
from qq919.settings import SECRET_KEY

def generate_jwt(user):
    payload={
        'uid':user.id,
        'username':user.mobile,
    }
    token=jwt.encode(payload=payload,key=SECRET_KEY,algorithm='HS256')
    return token





#登录
class Deng(APIView):
    def post(self,request):
        mobile=request.data.get('mobile')
        try:
            user=UserModel.objects.get(mobile=mobile)
        except:
            return Response({'code':204,'msg':'手机号错误'})
        token = generate_jwt(user)
        return Response({'code': 200,
                         'msg': '登录成功',
                         'token': token,
                         'user': {
                             'uid': user.id,
                             'username': user.mobile,
                         }
                         })



#验证码
from users.ser.wer import send_code
class Yan(APIView):
    def get(self,request):
        mobile=request.query_params.get('mobile')
        if not re.findall('^1[3-9]\d{9}$',mobile):
            return Response({'code':205,'msg':'手机号不正确'})
        # resp=send_message(mobile)   #。。。。。。。。。

        resp=send_code.delay(mobile)
        time.sleep(3)
        try:
           cls=redis.Redis(host='127.0.0.1',port=6379,password='123',db=5)
           key='celery-task-meta-'+resp.id
           redis_data=cls.get(key)

           if redis_data:
               distct_resp=json.loads(redis_data.decode())
               if  distct_resp['status']=='SUCCESS':
                  dict_data=json.loads(distct_resp['result'])
                  if  dict_data['statusCode']=='112310' or dict_data['statusCode']=='000000':
                     return  Response({'msg':'验证码发送成功','code':200})
               return Response({'code':201,'msg':'错误'})
           else:
                return  Response({'msg':'验证码发送失败','code':206})
        except  Exception as  e:
            print('错误原因',e)
            return Response({'code':500,'msg':'后端错误'})



#分类

class Fen(APIView):
    def get(self,request):
        set=HotelModel.objects.all()
        list=[]
        for i in set:
            list.append({
                'id':i.id,
                'name':i.name,

            })
        return Response(list)


class Xian(APIView):
    def get(self,request):
        se=request.query_params.get('id')
        set=SetModel.objects.filter(tt=se)
        list=[]
        for i in set:
            list.append({
                'id':i.id,
                'name':i.name,
                'set':i.set,
                'tt':i.tt_id,
            })
        return Response(list)